package org.example.forkjoin;

import java.util.concurrent.RecursiveTask;

public class RecursiveSumTask extends RecursiveTask<Integer> {

    private static final long serialVersionUID = 1L;
    private static final int THRESHOLD = 10; // 阈值，小于这个阈值时直接计算总和
    private final int[] array;
    private final int start;
    private final int end;

    public RecursiveSumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if (end - start <= THRESHOLD) { // 如果数组片段足够小，直接计算总和
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
        } else { // 否则，将任务拆分为两个子任务
            int middle = (start + end) / 2;
            RecursiveSumTask leftTask = new RecursiveSumTask(array, start, middle);
            RecursiveSumTask rightTask = new RecursiveSumTask(array, middle, end);

            leftTask.fork(); // 异步执行左半部分
            rightTask.fork(); // 异步执行右半部分

            sum = leftTask.join() + rightTask.join(); // 等待两个子任务完成并合并结果
        }
        return sum;
    }
}
